import traceback
from pathlib import Path


import sys
bath_dir = Path(__file__).parent.parent
sys.path.append(bath_dir.as_posix())

from webapp.plugins.image_utils import file2webp
from multiprocessing.dummy import Pool as ThreadPool
from queue import Queue, Empty
from tools import upload

# 包含子目录的图片
SUB_DIR = False
# 图片质量
quality = 85
# 原图文件夹
img_dir = r''
# 缩放比例
resize_factor = 1
# 生成缩略图
make_thumb = True
path = Path(img_dir)  # 原始图片文件夹
if SUB_DIR:
    path_iterator = path.rglob("*")
else:
    path_iterator = path.iterdir()
image_list = []
for file in path_iterator:
    if file.suffix.lower() in ('.jpg', '.jpeg', '.png', '.gif', '.webp'):
        image_list.append(file)
image_list.sort(reverse=True)
q = Queue()
for i in image_list:
    q.put(i)


def worker(num):
    try:
        while not q.empty():
            file_path = q.get()
            img_dict = file2webp(file_path, quality=quality, resize_factor=resize_factor, make_thumb=make_thumb)
            if img_dict['convert']:
                filename = file_path.stem + '.webp'  # 图片保留原文件名，修改后缀为webp
            else:
                filename = file_path.name
            result = upload(filename, img_dict)
            img_dict['file_name'] = file_path.name
            img_dict['upload_status'] = result['status']
            img_dict['upload_status_alias'] = result['msg']
            img_dict.pop('img_buffer')
            img_dict.pop('thumb_buffer')
            print(q.qsize(), img_dict)
    except Empty:
        return
    except:
        print(img_dict, traceback.format_exc())

pool = ThreadPool(4)
pool.map(worker, range(3))
